<template>
  <div class="app-container">
    <div v-loading="addLoading" class="coupon-type">
      <el-row type="flex" class="row-bg" justify="space-between">
        <el-col :span="4">
          <div class="grid-content title">礼券基础信息维护</div>
        </el-col>
        <el-col :span="2">
          <div class="grid-content bg-purple">
            <el-button type="primary" style="float: right;" @click="handleGoBack">返回</el-button>
          </div>
        </el-col>
      </el-row>
      <el-form ref="info" label-position="left" :model="info" inline label-width="100px" style="margin-top: 20px;">
        <div class="common coupon-name">
          <el-form-item label="名称">
            <el-input v-model="info.name" placeholder="请输入礼券名称" style="width: 200px" />
          </el-form-item>
          <el-form-item label="礼券类型">
            <el-radio
              v-for="item of couponTypeList"
              :key="item.id"
              v-model="info.couponType"
              :label="item.id"
            >
              {{ item.name }}
            </el-radio>
            <span class="coupon-desc">( 如不发送礼券，请选择其他 )</span>
          </el-form-item>
        </div>
        <div class="common">
          <el-form-item label="促销类型">
            <el-select v-model="info.promotion" placeholder="促销类型">
              <el-option
                v-for="promotion of promotionList"
                :key="promotion.value"
                :label="promotion.text"
                :value="promotion.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送消息类型">
            <el-select v-model="info.type" placeholder="发送消息类型" @change="handleTypeChange">
              <el-option
                v-for="type of typeList"
                :key="type.value"
                :label="type.text"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="common">
          <el-form-item label="有效日期">
            <el-date-picker
              v-model="info.startDate"
              type="date"
              placeholder="开始时间"
              value-format="yyyy-MM-dd"
              style="width: 200px"
            />
            <span class="gap">至</span>
            <el-date-picker
              v-model="info.endDate"
              type="date"
              placeholder="结束时间"
              value-format="yyyy-MM-dd"
              style="width: 200px"
            />
          </el-form-item>
          <div class="date-desc">注：超出该有效期，则不会发放该券。建议设置小于等于CRM中的有效期</div>
        </div>
      </el-form>
      <!-- 企业微信群发消息模板配置 -->
      <el-row v-if="info.type === '00'" style="margin-top: 20px">
        <el-col :span="6">
          <div class="grid-content title template-title">
            <span>企业微信群发消息模板配置</span>
            <span class="template-info">(店长端展示预览)</span>
          </div>
        </el-col>
      </el-row>
      <!-- 模板配置区域 -->
      <!-- 图文链接消息 -->
      <el-row v-if="info.type === '00'">
        <el-col :span="16">
          <div class="template-config">
            <el-row>
              <el-col :span="18">
                <div class="desc-common theme">
                  <span>标题</span>
                  <el-input v-model="title" placeholder="消息标题" style="width:90%" />
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <div class="desc-common desc">
                  <span>描述</span>
                  <el-input
                    v-model="desc"
                    type="textarea"
                    :rows="6"
                    placeholder="消息描述"
                    style="width: 90%;"
                  />
                  <img class="desc-image" :src="picUrl">
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="desc-common upload">
                  <span>图片</span>
                  <el-upload
                    v-loading="uploadLoading"
                    class="avatar-uploader"
                    :headers="headers"
                    :file-list="fileList"
                    action=""
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleUploadImage"
                  >
                    <img v-if="picUrl" :src="picUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>

                  <span class="link-url">图片跳转链接</span>
                  <el-input
                    v-model="linkUrl"
                    placeholder="请输入跳转链接"
                    style="width: 240px;"
                  />
                </div>
                <div class="care-info link">注：图片小于2MB，支持JPG、PNG格式</div>
              </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
              <el-col :span="18">
                <div class="desc-common desc-no-pic">
                  <span>文本消息</span>
                  <el-input
                    v-model="content"
                    type="textarea"
                    :rows="6"
                    placeholder="文本消息（可不选）"
                    style="width: 90%;"
                  />
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <!-- 跳转小程序样式 -->
      <el-row v-if="info.type === '01'">
        <el-col :span="24">
          <el-form
            ref="info"
            :model="info"
            label-width="100px"
            style="margin-top: 20px;"
            :label-position="labelPosition"
          >
            <el-form-item label="消息标题">
              <el-input v-model="title" style="width: 200px" />
            </el-form-item>
            <el-form-item label="消息封面">
              <el-upload
                v-loading="uploadLoading"
                class="avatar-uploader"
                :headers="headers"
                :file-list="fileList"
                action=""
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :http-request="handleUploadImageMini"
              >
                <img v-if="picMediaId" :src="picMediaId" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <div class="care-info">注：图片小于2MB，支持JPG、PNG格式</div>
            </el-form-item>
            <el-form-item label="小程序appid">
              <el-input v-model="appId" style="width: 200px" />
            </el-form-item>
            <el-form-item label="跳转路径">
              <el-input v-model="page" style="width: 200px" />
            </el-form-item>
            <el-form-item label="文本消息" style="width: 600px;">
              <el-input
                v-model="content"
                type="textarea"
                :rows="6"
                placeholder="文本消息（可不选）"
                style="width: 90%;"
              />
            </el-form-item>
          </el-form>
        </el-col>
        <div class="mini-show">
          <h4 class="mini-show-title">发送消息预览</h4>
          <div class="mini-show-content">
            <h5 class="info-title">{{ title }}</h5>
            <img class="mini-show-pic" :src="picMediaId">
            <div class="mini-show-footer">
              <img :src="mini">
              <span>小程序</span>
            </div>
          </div>
        </div>
      </el-row>
      <!-- 图文非链接消息 -->
      <el-row v-if="info.type === '02'">
        <el-col :span="16">
          <div class="template-config">
            <el-row>
              <el-col :span="18">
                <div class="desc-common desc-no-pic">
                  <span>文本消息</span>
                  <el-input
                    v-model="content"
                    type="textarea"
                    :rows="6"
                    placeholder="文本消息（可不选）"
                    style="width: 90%;"
                  />
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="desc-common upload">
                  <span>图片</span>
                  <el-upload
                    v-loading="uploadLoading"
                    class="avatar-uploader"
                    :headers="headers"
                    :file-list="fileList"
                    action=""
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleUploadImage"
                  >
                    <img v-if="picUrl" :src="picUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </div>
                <div class="care-info link">注：图片小于2MB，支持JPG、PNG格式</div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row
        v-if="(info.type === '00' || info.type === '02') && info.couponType !== 3"
        style="margin-top: 20px;margin-left: 15px;"
      >
        <el-form :inline="true">
          <el-form-item label="礼券ID">
            <el-input v-model="couponId" placeholder="礼券ID（必填）" />
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="confirm-cancel">
            <el-button type="primary" @click="handleConfirmInfo">确认</el-button>
            <el-button type="info" plain @click="handleCancelInfo">取消</el-button>
            <!-- <input type="file" @change="handleChange">上传</input> -->
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { uploadImage } from '@/api/coupon/common'
import { getToken } from '@/utils/auth'
import { DateModel } from '@/utils/date.js'
import { compressImg } from '@/utils/compressor.js'
import { getCreateCoupon, getUpdateCoupon } from '@/api/coupon/coupon'
import mini from '@/assets/images/mini.png'
export default {
  name: 'CouponType',
  data() {
    return {
      mini: mini,
      uploadLoading: false,
      headers: {
        'Authorization': getToken()
      },
      fileList: [],
      promotionList: [
        {
          value: '00',
          text: '满减'
        },
        {
          value: '01',
          text: '折扣'
        },
        {
          value: '02',
          text: '赠品'
        }
      ],
      typeList: [
        {
          value: '00',
          text: '图文链接'
        },
        {
          value: '01',
          text: '跳转小程序'
        },
        {
          value: '02',
          text: '图文非链接'
        }
      ],
      /* 礼券类型列表 */
      couponTypeList: [{
        id: 1,
        name: 'CRM券'
      }, {
        id: 2,
        name: '有赞券'
      }, {
        id: 3,
        name: '其他'
      }],
      info: {
        name: '',
        promotion: '00',
        type: '00',
        startDate: '',
        endDate: '',
        couponType: 1
      },
      /**
       * 标题、描述、图片链接、消息跳转链接
       */
      title: '',
      content: '',
      desc: '',
      picUrl: '',
      linkUrl: '',
      pictureUrl: '',
      upload_url: '',
      addLoading: false,
      /* 跳转小程序 */
      picMediaId: '', // 消息封面图片
      appId: '',
      page: '',
      couponId: '', // 礼券ID
      /**
       * 标识此次动作是更新还是新增礼券
       * 00 默认新增
       * 01 从礼券发放设定跳转过来
       * 02 编辑原有礼券信息
       */
      editType: '00',
      id: '', // 更改礼券信息时，需要给一个id
      labelPosition: 'left'
    }
  },
  computed: {
    couponIdText() {
      const { couponType, type } = this.info
      console.log(couponType, type)
      if ((type === '00' || type === '02') && couponType !== 3) {
        return '礼券ID(必填)'
      } else {
        return '礼券ID(可选)'
      }
    }
  },
  created() {
    this.setDefaultDate()
    this.getRouteParam()
  },
  methods: {
    handleChange(e) {
      console.log(e)
    },
    handleTypeChange() {
      console.log('change')
      /**
       * 图文链接消息和图文非链接消息切换时，清除原有数据
       */
      this.desc = ''
      this.content = ''
      this.picUrl = ''
    },
    handleGoBack() {
      this.$router.go(-1)
    },
    async handleConfirmInfo() {
      console.log('确认')
      const {
        info,
        id,
        title,
        content,
        desc,
        picUrl,
        linkUrl,
        appId,
        picMediaId,
        page,
        couponId } = this
      const { name, startDate, endDate, type, couponType } = info
      if (!name) {
        this.$message('请输入优惠券名称')
        return
      }
      if (!startDate) {
        this.$message('请输入礼券有效时间')
        return
      }
      if (!endDate) {
        this.$message('请输入礼券有效时间')
        return
      }
      /**
       * type 00 01
       */
      if (type === '00') {
        if (!title) {
          this.$message('请输入消息标题')
          return
        }
        if (!desc) {
          this.$message('请输入消息描述')
          return
        }
        if (!linkUrl) {
          this.$message('请输入消息跳转链接')
          return
        }
        if (!picUrl) {
          this.$message('请上传图片')
          return
        }
      } else if (type === '01') {
        if (!title) {
          this.$message('请输入消息标题')
          return
        }
        if (!picMediaId) {
          this.$message('请上传消息封面图片')
          return
        }
        if (!appId) {
          this.$message('请输入小程序appid')
          return
        }
        if (!page) {
          this.$message('请输入小程序跳转链接')
          return
        }
      } else if (type === '02') {
        if (!content && !picUrl) {
          this.$message('请输入消息内容或消息图片')
          return
        }
      }
      console.log(info)
      const requestData = { ...this.info }
      /**
       * 00 图文链接
       * 01 跳转小程序
       * 02 图文非链接
       */
      if (type === '00') {
        requestData.title = title
        requestData.desc = desc
        requestData.picUrl = picUrl
        requestData.linkUrl = linkUrl
        if (content) {
          requestData.content = content
        }
      } else if (type === '01') {
        requestData.title = title
        requestData.pic_media_id = picMediaId
        requestData.appid = appId
        requestData.page = page
        if (content) {
          requestData.content = content
        }
      } else if (type === '02') {
        if (content) {
          requestData.content = content
        }
        requestData.picUrl = picUrl
      }
      /**
       * 是否需要输入礼券id
       * couponType 1 || 2  && type 00 || 02
       * 图文链接 图文非链接 礼券类型选择crm或有赞时是必填
       */
      if ((couponType === 1 || couponType === 2) && (type === '00' || type === '02')) {
        if (!couponId) {
          this.$message('请输入礼券ID')
          return
        }
        requestData.couponId = couponId
      }
      console.log(requestData)
      this.addLoading = true
      setTimeout(() => {
        this.addLoading = false
      }, 6000)
      if (this.editType === '02') {
        requestData.id = id
        await getUpdateCoupon(requestData)
        this.addLoading = false
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      } else {
        await getCreateCoupon(requestData)
        this.addLoading = false
        this.$message({
          message: '新增成功',
          type: 'success'
        })
      }
      this.setDefaultTypeinfo()
      this.editType = '00'
      this.$router.go(-1)
      // if (this.editType !== '00') {
      //   this.editType = '00'
      //   this.$router.go(-1)
      // }
    },
    handleCancelInfo() {
      try {
        this.$router.go(-1)
      } catch (err) {
        this.$router.push('/dashboard')
      }
    },
    /**
     * 上传图片方法
     */
    async handleUploadImage(e) {
      const _this = this
      const { file } = e
      compressImg(file).then(async(compressFile) => {
        const requestData = {
          base64Img: compressFile.split(',')[1]
        }
        _this.uploadLoading = true
        setTimeout(() => {
          _this.uploadLoading = false
        }, 5000)
        const baseRes = await uploadImage(requestData)
        _this.uploadLoading = false
        _this.$message({
          message: '图片上传成功',
          type: 'success'
        })
        _this.picUrl = baseRes.imgUrl
      })
        .catch(error => {
          console.log(error)
          this.$message(error)
        })
    },
    async handleUploadImageMini(e) {
      const _this = this
      const { file } = e
      compressImg(file).then(async(compressFile) => {
        const requestData = {
          base64Img: compressFile.split(',')[1]
        }
        _this.uploadLoading = true
        setTimeout(() => {
          _this.uploadLoading = false
        }, 5000)
        const baseRes = await uploadImage(requestData)
        _this.uploadLoading = false
        _this.$message({
          message: '图片上传成功',
          type: 'success'
        })
        _this.picMediaId = baseRes.imgUrl
      })
        .catch(error => {
          console.log(error)
          this.$message(error)
        })
    },
    handleAvatarSuccess(e) {
      console.log('success', e)
    },
    beforeAvatarUpload(file) {
      console.log('before upload')
    },
    /**
     * 初始化礼券信息数据
     */
    setDefaultTypeinfo() {
      this.title = ''
      this.desc = ''
      this.picUrl = ''
      this.linkUrl = ''
      this.info.name = ''
      this.setDefaultDate()
    },
    setDefaultDate() {
      const curDate = DateModel.getCurDate()
      this.info.startDate = curDate
      this.info.endDate = curDate
    },
    /**
     * 页面初始化
     * 获取路由传递过来的参数
     */
    getRouteParam() {
      const { params } = this.$route
      const { editType } = params
      console.log('params is', params)
      if (editType) {
        this.editType = editType
        if (editType === '02' && JSON.stringify(params) !== '{}') {
          this.id = params.id
          this.title = params.title

          this.info.name = params.name
          this.info.promotion = params.promotion
          this.info.type = params.type
          this.info.couponType = params.couponType
          this.couponId = params.couponId
          // 时间处理
          const { date } = params
          const dateArr = date.split('~')
          const startDate = dateArr[0].split(' ')
          const endDate = dateArr[1].split(' ')
          this.info.startDate = startDate[0]
          this.info.endDate = endDate[0]

          if (params.type === '01') {
            this.picMediaId = params.pic_media_id
            this.appId = params.appid
            this.page = params.page
            if (params.content) {
              this.content = params.content
            }
          } else if (params.type === '00') {
            this.desc = params.desc
            this.picUrl = params.picUrl
            this.linkUrl = params.linkUrl
            if (params.content) {
              this.content = params.content
            }
          } else if (params.type === '02') {
            this.content = params.content
            this.picUrl = params.picUrl
          }
        }
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .coupon-type{
    width: 100%;
    min-height: 90px;
    border-radius: 6px;
    background: #ffffff;
    padding-top: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
    padding-right: 20px;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
    .title{
      font-size: 14px;
      color: #606266;
      color: #333;
    }
    .common{
      .gap{
        color: #606266;
        margin: 0 10px;
      }
      .date-desc{
        margin-top: -12px;
        padding-left: 34px;
        font-size: 13px;
        color: #f56c6c;
      }
      .coupon-desc{
        font-size: 13px;
        color: #606266;
        margin-left: -30px;
      }
    }
    .template-title{
      position: relative;
      height: 28px;
      .template-info{
        position: absolute;
        font-size: 12px;
        color: #606266;
        top: 20px;
        left: 0px;
      }
    }
    .template-config{
      padding: 15px;
      background: #FAFAFA;
      margin-top: 10px;
      border-radius: 2px;
      .desc-common{
        margin: 10px 0;
        display: flex;
        &.theme{
          align-items: center;
        }
        span{
          margin-right: 20px;
          font-size: 14px;
          color: #606266;
          font-weight: 700;
        }
        &.upload{
          display: flex;
          align-items: center;
          .link-url{
            margin-left: 40px;
          }
        }
      }
      .desc{
        position: relative;
        .desc-image{
          position: absolute;
          top: 17px;
          right: 22px;
          width: 85px;
          height: 85px;
          background: #f8f8f8;
        }
      }
      .desc-no-pic{
        .el-textarea__inner{
          padding-right: 0;
        }
      }
    }
    .confirm-cancel{
      margin-left: 8px;
      margin-top: 30px;
      margin-bottom: 10px;
    }
  }
  .care-info{
    margin-left: -66px;
    margin-top: -10px;
    font-size: 13px;
    color: #f56c6c;
    &.link{
      margin-top: 0px;
      margin-left: 3px;
    }
  }
  /* 跳转小程序消息预览 */
  .mini-show{
    position: absolute;
    top: 0px;
    left: 390px;
    width: 170px;
    font-size: 14px;
    color: #f56c6c;
    .mini-show-title{
      color: #333;
      font-weight: normal;
      margin-top: 20px;
      margin-bottom: 10px;
    }
    .mini-show-content{
      border: 1px dashed #d9d9d9;
      padding: 10px;
      background: #f8f8f8;
      .info-title{
        font-size: 14px;
        font-weight: 600;
        color: #1f1f1f;
        margin-top: 0px;
        margin-bottom: 10px;
      }
      .mini-show-pic{
        width: 150px;
        height: 120px;
      }
      .mini-show-footer{
        display: flex;
        align-items: center;
        margin-top: 10px;
        img{
          width: 16px;
          height: 16px;
        }
        span{
          font-size: 14px;
          color: #a8a8a8;
          margin-left: 3px;
        }
      }
    }
  }
</style>

<style>
  .desc .el-textarea__inner{
    padding-right: 150px;
    border: none;
  }
  /* 上传样式 */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 85px;
    height: 85px;
    line-height: 85px;
    text-align: center;
  }
  .avatar {
    width: 85px;
    height: 85px;
    display: block;
  }
</style>
